<template>
  <div id="spaceDetailPage">
    <!-- 空间信息 -->
    <div class="space-header">
      <a-flex justify="space-between" align="center">
        <div class="space-title">
          <h2>{{ space.spaceName }}</h2>
          <span class="space-type">个人空间</span>
        </div>
        <a-space size="middle" class="action-buttons">
          <a-button
            type="primary"
            size="large"
            :href="`/add_picture?spaceId=${id}`"
            target="_blank"
          >
            <PlusOutlined /> 上传图片
          </a-button>
          <a-button
            type="primary"
            ghost
            size="large"
            :href="`/space_analyze?spaceId=${id}`"
            target="_blank"
          >
            <BarChartOutlined /> 数据统计
          </a-button>
          <a-button size="large" @click="doBatchEdit"> <EditOutlined /> 批量管理 </a-button>
          <div class="space-usage">
            <a-tooltip
              :title="`已使用空间 ${formatSize(space.totalSize)} / ${formatSize(space.maxSize)}`"
            >
              <a-progress
                type="circle"
                :size="48"
                :percent="((space.totalSize * 100) / space.maxSize).toFixed(1)"
                :strokeColor="{
                  '0%': '#ff9a9e',
                  '100%': '#fad0c4',
                }"
              />
            </a-tooltip>
          </div>
        </a-space>
      </a-flex>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <PictureSearchForm :onSearch="onSearch" />

      <div class="color-search">
        <div class="color-search-title">
          <SwatchIcon class="icon" />
          颜色筛选
        </div>
        <color-picker
          format="hex"
          @pureColorChange="onColorChange"
          :colors="['#ff9a9e', '#fad0c4', '#ffeaea']"
        />
      </div>
    </div>

    <!-- 图片列表 -->
    <PictureList
      :dataList="dataList"
      :loading="loading"
      :showOp="true"
      :hasMore="hasMore"
      :onReload="fetchData"
      @loadMore="loadMore"
    />

    <BatchEditPictureModal
      ref="batchEditPictureModalRef"
      :spaceId="id"
      :pictureList="dataList"
      :onSuccess="onBatchEditPictureSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { h, onMounted, ref } from 'vue'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController.ts'
import { message } from 'ant-design-vue'
import {
  listPictureVoByPageUsingPost,
  searchPictureByColorUsingPost,
} from '@/api/pictureController.ts'
import { formatSize } from '@/utils'
import PictureList from '@/components/PictureList.vue'
import PictureSearchForm from '@/components/PictureSearchForm.vue'
import { ColorPicker } from 'vue3-colorpicker'
import 'vue3-colorpicker/style.css'
import BatchEditPictureModal from '@/components/BatchEditPictureModal.vue'
import { BarChartOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { SwatchIcon } from '@heroicons/vue/24/outline'

interface Props {
  id: string | number
}

const props = defineProps<Props>()
const space = ref<API.SpaceVO>({})

// -------- 获取空间详情 --------
const fetchSpaceDetail = async () => {
  try {
    const res = await getSpaceVoByIdUsingGet({
      id: props.id,
    })
    if (res.data.code === 0 && res.data.data) {
      space.value = res.data.data
    } else {
      message.error('获取空间详情失败，' + res.data.message)
    }
  } catch (e: any) {
    message.error('获取空间详情失败：' + e.message)
  }
}

onMounted(() => {
  fetchSpaceDetail()
  fetchData()
})

// --------- 获取图片列表 --------

// 定义数据
const dataList = ref<API.PictureVO[]>([])
const loading = ref(true)
const hasMore = ref(true)

// 搜索条件
const searchParams = ref<API.PictureQueryRequest>({
  current: 1,
  pageSize: 12,
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 获取数据
const fetchData = async (isLoadMore = false) => {
  if (!isLoadMore) {
    loading.value = true
  }

  try {
    const params = {
      spaceId: props.id,
      ...searchParams.value,
    }
    const res = await listPictureVoByPageUsingPost(params)
    if (res.data.code === 0 && res.data.data) {
      const records = res.data.data.records ?? []
      if (isLoadMore) {
        dataList.value.push(...records)
      } else {
        dataList.value = records
      }
      hasMore.value = dataList.value.length < (res.data.data.total ?? 0)
    } else {
      message.error('获取数据失败，' + res.data.message)
    }
  } catch (error) {
    message.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  if (!hasMore.value || loading.value) return
  searchParams.value.current++
  fetchData(true)
}

// 搜索
const onSearch = (newSearchParams: API.PictureQueryRequest) => {
  searchParams.value = {
    ...searchParams.value,
    ...newSearchParams,
    current: 1,
  }
  hasMore.value = true
  dataList.value = []
  fetchData()
}

// 按照颜色搜索
const onColorChange = async (color: string) => {
  loading.value = true
  try {
    const res = await searchPictureByColorUsingPost({
      picColor: color,
      spaceId: props.id,
    })
    if (res.data.code === 0 && res.data.data) {
      dataList.value = res.data.data ?? []
      hasMore.value = false // 颜色搜索不支持分页
    } else {
      message.error('获取数据失败，' + res.data.message)
    }
  } catch (error) {
    message.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// ---- 批量编辑图片 -----
const batchEditPictureModalRef = ref()

// 批量编辑图片成功
const onBatchEditPictureSuccess = () => {
  fetchData()
}

// 打开批量编辑图片弹窗
const doBatchEdit = () => {
  if (batchEditPictureModalRef.value) {
    batchEditPictureModalRef.value.openModal()
  }
}
</script>

<style scoped>
#spaceDetailPage {
  margin-bottom: 24px;
}

.space-header {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(255, 255, 255, 0.95) 100%);
  padding: 24px;
  border-radius: 16px;
  margin-bottom: 24px;
  box-shadow:
    0 4px 20px rgba(255, 182, 182, 0.1),
    0 0 0 1px rgba(255, 228, 228, 0.5);
}

.space-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.space-title h2 {
  margin: 0;
  font-size: 24px;
  background: linear-gradient(135deg, #d4463d 0%, #ff6b6b 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.space-type {
  padding: 4px 12px;
  background: rgba(212, 70, 61, 0.1);
  color: #d4463d;
  border-radius: 20px;
  font-size: 14px;
}

.action-buttons :deep(.ant-btn) {
  border-radius: 8px;
  height: 40px;
  padding: 0 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.space-usage {
  padding: 4px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(255, 182, 182, 0.1);
}

.search-section {
  background: rgba(255, 255, 255, 0.8);
  padding: 24px;
  border-radius: 12px;
  margin-bottom: 24px;
  box-shadow:
    0 2px 12px rgba(255, 182, 182, 0.08),
    0 0 0 1px rgba(255, 228, 228, 0.3);
}

.color-search {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid rgba(255, 228, 228, 0.5);
}

.color-search-title {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  margin-bottom: 16px;
  font-weight: 500;
}

.color-search-title .icon {
  width: 20px;
  height: 20px;
  color: #d4463d;
  transition: transform 0.3s ease;
}

.color-search-title:hover .icon {
  transform: scale(1.1);
}

:deep(.vue-colorpicker) {
  border: 1px solid rgba(255, 228, 228, 0.5);
  border-radius: 8px;
  overflow: hidden;
}
</style>
